package com.czp.infosharingplatformapp.service.impl;

import com.czp.infosharingplatformapp.model.Message;
import com.czp.infosharingplatformapp.model.User;
import com.czp.infosharingplatformapp.repository.MessageRepository;
import com.czp.infosharingplatformapp.repository.UserRepository;
import com.czp.infosharingplatformapp.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageRepository messageRepository;

    @Autowired
    private UserRepository userRepository;

    @Override
    public Message createMessage(String content, Long userId, Long parentId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        Message parent = null;
        if (parentId != null) {
            parent = messageRepository.findById(parentId)
                    .orElseThrow(() -> new RuntimeException("父留言不存在"));
        }

        Message message = new Message();
        message.setContent(content);
        message.setUser(user);
        message.setParent(parent);
        message.setRead(false);

        return messageRepository.save(message);
    }

    @Override
    public List<Message> getAllMessages() {
        return messageRepository.findAll();
    }

    @Override
    public void deleteMessage(Long messageId) {
        if (!messageRepository.existsById(messageId)) {
            throw new RuntimeException("留言不存在");
        }
        messageRepository.deleteById(messageId); // 删除留言
    }

    @Override
    public List<Message> getMessagesByUserId(Long userId) {
        return messageRepository.findByUserId(userId);
    }

    @Override
    public List<Message> getUnreadMessagesByUserId(Long userId) {
        List<Message> unreadMessages = messageRepository.findByUserIdAndIsReadFalse(userId);
        for (Message message : unreadMessages) {
            message.setRead(true); // 设置为已读
        }
        messageRepository.saveAll(unreadMessages); // 保存修改
        return unreadMessages;
    }
}